package com.sky.web.app;

import com.sky.dto.DishPageDTO;
import com.sky.result.Result;
import com.sky.service.DishService;
import com.sky.vo.DishVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

@RestController
@RequestMapping("/user/dish")
@Slf4j
public class AppDishController {

    @Autowired
    private DishService dishService;

    @Autowired
    private RedisTemplate redisTemplate;

    //根据分类id查询菜品列表
    @GetMapping("/list")
    public Result findList(Long categoryId) {
        //1.先查询radis中有没有缓存,有就直接返回
        String key = "DISH:" + categoryId;
        if (redisTemplate.hasKey(key)) {
            log.info("查询redis");
            return Result.success(redisTemplate.opsForValue().get(key));
        } else {
            log.info("查询数据库");
            //2.如果缓存没有,在查询数据库,同步缓存
            DishPageDTO dishPageDTO = DishPageDTO.builder()
                    .categoryId(categoryId)
                    .status(1)//起售的菜品
                    .build();
            List<DishVO> list = dishService.findList(dishPageDTO);
            //3.同步缓存
            redisTemplate.opsForValue().set(key, list);
            return Result.success(list);
        }
    }
}
